import { useState } from 'react';
import { Trash } from 'lucide-react';

import { Checkbox } from './ui/checkbox';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { postCreateSubTask, postDeleteTask, postStatusTask } from '@/axios/taskBoard';

// const emptyCardTask = {
//   name: '',
//   id: 0,
//   column_id: 0,
//   end_date: null,
//   files: [],
//   is_closed: 0,
//   performers: [],
//   priority_id: null,
//   parent_id: 0,
//   status: null,
//   subtasks: [],
//   text: '',
//   type_id: null
// };

const Checklist = ({ subtasks }: { subtasks: Task[] }) => {
  const [items, setItems] = useState<Task[]>(() => {
    return subtasks ? subtasks : [];
  });
  const [name, setName] = useState('');

  const addItem = () => {
    if (name.trim() !== '') {
      const projectId = localStorage.getItem('selectedProjectId')
      postCreateSubTask({
        params: {
          name,
          parent_id: subtasks[0].parent_id,
          project_id: projectId || ''
        }
      });
      setName('');
    }
  };

  const toggleItem = (index: any) => {
    const newItems = [...items];
    const finder = items.findIndex((item) => item.id === index);
    const itemStatus = newItems[finder].is_closed === 1 ? 0 : 1;
    newItems[finder].is_closed = itemStatus;
    postStatusTask({
      params: {
        id: index,
        status: itemStatus
      }
    });
    setItems(newItems);
  };

  const removeItem = (index: number) => {
    const newItems = [...items];
    postDeleteTask({ params: { id: +newItems[index].id } });
    newItems.splice(index, 1);
    setItems(newItems);
  };

  return (
    <div>
      <ul className='w-fulll'>
        {items.map((item, index) => (
          <li
            key={index}
            className='group flex w-full items-center border-b border-gray-200 p-2 transition-all  hover:bg-gray-100'
          >
            <Checkbox
              checked={!!item.is_closed}
              onClick={() => {
                toggleItem(item.id);
              }}
            />
            <span
              className='ml-1 mr-6'
              style={{
                textDecoration: item.is_closed ? 'line-through' : 'none'
              }}
            >
              {item.name}
            </span>
            <Button
              variant='outline'
              className='ml-auto p-1 opacity-0 transition-all group-hover:opacity-100'
              onClick={() => removeItem(index)}
            >
              <Trash size={14} color='red' />
            </Button>
          </li>
        ))}
      </ul>

      <Input
        type='text'
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder='Enter item...'
        className='mt-5'
      />
      <Button className='ml-auto mt-2  ' onClick={addItem}>
        Add Item
      </Button>
    </div>
  );
};

export default Checklist;
